package com.kingyea.app.market.utils;

import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * 文件上传工具
 *
 * @author Mr.Lin
 * @version v1.0.0
 * @description
 * @date Created in 2017/11/21 10:30
 */
public class UploadUtils {


    /**
     * 文件上传
     *
     * @param file
     * @param filePath
     * @return java.io.File
     * @author Mr.Lin
     * @date 2017/11/21 10:34
     */
    public static File uploadFile(MultipartFile file, String filePath) throws Exception {
        String fileName = file.getOriginalFilename();
        System.out.println("源文件名：" + fileName);
        fileName = UUID.randomUUID().toString().replaceAll("-", "") + fileName.substring(fileName.lastIndexOf("."));
        System.out.println("临时文件名：" + fileName);
        File targetFileDir = new java.io.File(filePath);
        if (!targetFileDir.exists()) {
            targetFileDir.mkdirs();
        }
        String targetFileAbsolutePath = filePath + java.io.File.separator + fileName;
        File targetFile = new java.io.File(targetFileAbsolutePath);
        // 文件不存在就写入
        if (!targetFile.exists()) {
            FileOutputStream out = new FileOutputStream(targetFileAbsolutePath);
            out.write(file.getBytes());
            out.flush();
            out.close();
        }
        System.out.println(" temp file:" + targetFile.getCanonicalPath());
        // 计算MD5
        String hashType = "MD5";
        String md5FileName = Md5CaculateUtil.getHash(targetFile.getCanonicalPath(), hashType);
        md5FileName = md5FileName + fileName.substring(fileName.lastIndexOf(".") <= 0 ? fileName.length() - 1 : fileName.lastIndexOf("."));
        renameFile(filePath, fileName, md5FileName);
        deleteFile(targetFile.getCanonicalPath());
        targetFile = new File(filePath + java.io.File.separator + md5FileName);
        System.out.println(" new file:" + targetFile.getCanonicalPath());
        return targetFile;
    }


    /**
     * 多文件上传
     *
     * @param files
     * @param filePath
     * @return java.util.List<java.io.File>
     * @author Mr.Lin
     * @date 2017/11/21 10:35
     */
    public static List<File> uploadFiles(MultipartFile[] files, String filePath) throws Exception {
        List<File> fileList = new ArrayList<File>();
        for (MultipartFile file : files) {
            fileList.add(uploadFile(file, filePath));
        }
        return fileList;
    }


    /**
     * 文件重命名
     *
     * @param path    文件目录
     * @param oldname 原来的文件名
     * @param newname 新文件名
     * @author Mr.Lin
     * @date 2017/11/29 10:35
     */
    public static void renameFile(String path, String oldname, String newname) {
        if (!oldname.equals(newname)) {//新的文件名和以前文件名不同时,才有必要进行重命名
            File oldfile = new File(path + "/" + oldname);
            File newfile = new File(path + "/" + newname);
            if (!oldfile.exists()) {
                return;//重命名文件不存在
            }
            if (newfile.exists())//若在该目录下已经有一个文件和新文件名相同，则不允许重命名
                System.out.println(newname + " File already exists ! ");
            else {
                oldfile.renameTo(newfile);
            }
        } else {
            System.out.println(" The new file name is the same as the old file name ...");
        }
    }

    /**
     * 删除单个文件
     *
     * @param fileName 要删除的文件的文件名
     * @return 单个文件删除成功返回true，否则返回false
     * @author Mr.Lin
     * @date 2017/11/29 10:35
     */
    public static boolean deleteFile(String fileName) {
        File file = new File(fileName);
        // 如果文件路径所对应的文件存在，并且是一个文件，则直接删除
        if (file.exists() && file.isFile()) {
            if (file.delete()) {
                System.out.println(" delete file " + fileName + " success! ");
                return true;
            } else {
                System.out.println(" delete file " + fileName + " fail! ");
                return false;
            }
        } else {
            System.out.println(" delete file fail ：" + fileName + " Non-existent! ");
            return false;
        }
    }

    public static String getResourcesPath() {
        String jarDir = UploadUtils.class.getClassLoader().getResource("").getPath();
        System.out.println(jarDir);
        jarDir = jarDir.replaceAll("file:", "");
        jarDir = jarDir.substring(0, jarDir.indexOf("market-"));
        System.out.println(jarDir);
        String path = new java.io.File(jarDir + "../default/static").getAbsolutePath();
        return path;
    }

    public static void main(String[] args) {
        System.out.println(getResourcesPath());
    }
}